#include <iostream>
#include <mysql/mysql.h>
#include <jsoncpp/json/json.h>
#include <stdlib.h>
#include <unistd.h>
#include "common.hpp"
#include"../log.hpp"
using namespace std;
extern Log lg;
// 通过method来获取参数的方法
bool getQueryString(std::string &query)
{
    std::string method;
    method = getenv("METHOD");
    if ("GET" == method)
    {
        // 不对get请求处理
        return false;
    }
    else if ("POST" == method)
    {

        // POST方法参数通过管道传
        if (getenv("CONTENT_LENGTH") == NULL)
        {
            std::cerr << "获取正文长度参数失败!!!" << std::endl;
            return false;
        }
        int len = atoi(getenv("CONTENT_LENGTH"));
        // std::cerr<<"DEBUG:"<<len<<std::endl;
        char ch;
        while (len)
        {
            ssize_t n = read(0, &ch, 1);
            if (n > 0)
            {
                query.push_back(ch);
                len--;
            }
            else
            {
                return false;
            }
        }
        std::cerr << "DEBUG: 读取正文参数成功!!" << std::endl;
        return true;
    }
    return false;
}

int mysql_create(const string &title, const string &text, const string &token)
{
    cerr<<"DEBUG:--------------------------1"<<endl;
    stringstream ss;
    string userid;
    if (!AuthMiddleware::verify_token(token, userid))
        return -4;
    cerr << "DEBUG:userid=  " << userid << endl;

    MYSQL *conn = mysql_init(nullptr);
    if (nullptr == mysql_real_connect(conn, "127.0.0.1", "ldcwd", "123456", "httptest", 3306, nullptr, 0))
    {
        std::cerr << " mysql connect error !!" << std::endl;
        return -5;
    }
    std::cerr << "sql connect success!! " << std::endl;
    ss << "insert into blogs(user_id,title,content) values("
       << userid << ",\'" << title << "\'" << ",\'" << text << "\'" << ");";
    cerr << "DEBUG: BLOGS SQL : " << ss.str() << endl;
    if (mysql_query(conn, ss.str().c_str()) != 0)
    {
        cerr << "SQL err--------------------" << endl;
    }
    cerr<<"SQL insert success!! 发布成功"<<endl;
    return 0;
}

// 移除冗余转义符
std::string sanitizeJson(const std::string& input) {
    // 去除外层包裹的引号
    if (input.size() >= 2 && input.front() == '"' && input.back() == '"') {
        return input.substr(1, input.size()-2);
    }
    
    // 替换JSON标准转义符
    std::string cleaned;
    for (size_t i = 0; i < input.size(); ++i) {
        if (input[i] == '\\') {
            switch (input[++i]) {
                case '"': cleaned += '"'; break;
                case '\\': cleaned += '\\'; break;
                case 'n': cleaned += '\n'; break;
                // 其他转义符处理...
                default: cleaned += input[i]; break;
            }
        } else {
            cleaned += input[i];
        }
    }
    return cleaned;
}
int main()
{
    lg.Enable(3);
    string Authorization;
    Authorization = getenv("Authorization");
//cerr<<"DEBUG : Auth: "<<Authorization;
string token=Authorization.substr(7);
//cerr<<"DEBUG : token: "<<token;

    string query_string;
    if (!getQueryString(query_string))
    {
        lg(ERROR,__LINE__,"getQueryString 获取参数失败");
        return -1;

    }
    // 对json字符串进行解析(反序列化)
  //  cerr << "DEBUG: QUERYSTRING: " << query_string << endl;
    Json::Value v;
    Json::Reader r;
    query_string=sanitizeJson(query_string);
    query_string=sanitizeJson(query_string);
//cerr<<"DEBUG: "<<query_string<<endl;
    bool success = r.parse(query_string, v);



    if (!success)
    {

        // 获取详细错误信息

        std::string error_msg = r.getFormattedErrorMessages();

        lg(ERROR,__LINE__,"JSON解析失败 : %s ",error_msg.c_str());

        //std::cerr << "JSON解析失败: " << error_msg << std::endl;

        throw std::runtime_error("JSON解析失败");
    }

    // 关键验证：根节点类型必须是对象

    if (!v.isObject())
    {

       // std::cerr << "根节点类型错误: 期望对象，实际类型为 " << v.type() << std::endl;
        lg(ERROR,__LINE__,"根节点类型错误 ");

        throw std::runtime_error("无效的JSON结构");
    }


    if (success)
    {
        //cerr << "DEBUG: SUCCESS" << endl;

        std::string title = v["title"].asString();
        std::string text = v["content"].asString();
       // cerr << "DEBUG: " << title << endl;
        //cerr << "DEBUG: " << text << endl;

        // if (!getToken(token))
        // {
        //     cerr<<"DEBUG: token error!!"<<endl;
        //     return -2;
        // }
        int n = mysql_create(title, text, token);
        // 返回json格式的blogs
        Json::Value v; // 万能对象结构体

        if (n == 0)
        {
            v["success"] = true;
            v["message"] = "发布成功";
        }
        else
        {
            v["success"] = false;
            v["message"] = "发布失败";
        }
        string ret;
        // 序列化JSON得到一个串
        Json::StyledWriter w;
        ret = w.write(v);
        //cerr<<"DEBUG: ret: "<<ret<<endl;
        cout << ret;
    }
    else
        return -6;
    return 0;
}